//
//  NSObject+HDChatOBOManager.m
//  app
//
//  Created by D on 15/5/27.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDChatOBOManager.h"
#import "HDLoginUserURL.h"
#import "SNFmdbManager.h"

@interface HDChatOBOManager ()

@property (nonatomic,strong) JKHttpClient * jkHttp;
@property (nonatomic,strong) SNUniteUrl * uniteUrl;
@property (nonatomic,strong) NSMutableArray * mutableArray;
@property (nonatomic,strong) FMDatabaseQueue * fmdbQueue;
@property (nonatomic,strong) SNFmdbManager * snFmdbManager;
@property (nonatomic,strong) NSString * isRefresh;
@property (nonatomic,strong) NSData * myData;
@property (nonatomic,strong) NSString * pmid;
@property (nonatomic,assign) BOOL includeChatList;
@property (nonatomic,assign) BOOL includeData;

@end

@implementation HDChatOBOManager

+(HDChatOBOManager *)shareManager
{
    AS_SINGLETON(HDChatOBOManager, manager,{
        manager = [[HDChatOBOManager alloc]init];
        manager.jkHttp = [[JKHttpClient alloc]init];
        manager.uniteUrl = [SNUniteUrl shareUniteUrl];
        manager.mutableArray = [NSMutableArray array];
//        HDAppDelegate * delegate = (HDAppDelegate*)[UIApplication sharedApplication].delegate;
//        manager.fmdbQueue  = delegate.fmdbQueue;
        manager.snFmdbManager = [SNFmdbManager shareManager];
        
    })
    return manager;
    
}

-(void)loadChatContentData:(HDChatOBOResult *)result People:(NSString*)fuid SendMsgTime:(NSString*)sendMsgTime OwnerAddId:(NSString*)ownerAddId
{
    
    if ([self.jkHttp isRunning]) {
        return;
    }
    NSString * getContent = [NSString stringWithFormat:@"%@?fuid=%@",self.uniteUrl.im_chatContentUrl,fuid];
    [self.jkHttp get:getContent result:^(JKResponse *resp) {
//        DLog(@"status = %@",resp.message);
        if (resp.OK) {
            result.success = YES;
//            DLog(@"content = %@",resp.content);
            result.pmid = resp.content[@"pmid"];
            [self ChatOBODataSourceWithArray:resp.content[@"data"] Peopleid:fuid SendMsgTime:sendMsgTime OwnerAddId:ownerAddId];
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
    }];
    
}
//发送聊天内容（文字或图片）
-(void)sendChatContent:(HDChatOBOSendMessageResult *)result People:(NSString*)fuid Params:(NSDictionary*)params Refresh:(NSString*)refresh sendMsgTime:(NSString*)sendMsgTime Index:(NSString*)index OwnerAddId:(NSString*)ownerAddId
{
    
    self.isRefresh = refresh;
    
    if ([self.jkHttp isRunning]) {
        return;
    }
    

    [self.jkHttp post:self.uniteUrl.im_chatSendUrl params:params result:^(JKResponse *resp) {
        
        if (resp.OK) {
           
            result.success = YES;
            
                result.index = index;
                [self ChatOBODataSourceWithArray:resp.content[@"result"] Peopleid:fuid SendMsgTime:sendMsgTime OwnerAddId:ownerAddId];
                result.lastDic = [resp.content[@"result"] lastObject];
                for (NSDictionary * dic in resp.content[@"result"]) {
                    result.pmid = dic[@"pmid"];
                }
                NSDictionary * dic = @{@"state":@"0"};

        }else if (resp.failure){
            NSDictionary * dic = @{@"state":@"2"};
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"flower" object:self userInfo:dic];
            result.time = sendMsgTime;
            [self upDataToDBWithFailure:fuid MessageTime:sendMsgTime];
            result.failure = YES;
        }
        [result invoke];

    }];
   

}

//向客服发送商品信息
-(void)sendShopContent:(HDChatShopResutl *)result People:(NSString*)fuid Params:(NSDictionary*)params
{
    
    [self.jkHttp cancelAll];
    
    [self.jkHttp post:self.uniteUrl.im_chatSendUrl params:params result:^(JKResponse *resp) {
        
//        DLog(@"%d",resp.status);
        
        if (resp.OK) {
            result.success = YES;
           
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
        
    }];
    
    
}


-(void)sendChatImage:(HDChatOBOSenImage*)result Params:(NSDictionary*)params ImageData:(NSData*)data sengMsgTime:(NSString*)sendMsgTime Index:(NSString*)index People:(NSString*)fuid OwnerAddId:(NSString*)ownerAddid
{
    if ([self.jkHttp isRunning]) {
        return;
    }
    [self.jkHttp upload:self.uniteUrl.imm_chatImageUrl data:data params:params result:^(JKResponse *resp) {
        if (resp.OK) {
            result.success = YES;
            result.index = index;
            result.ownerId = ownerAddid;
            result.picture = [resp.content objectForKey:@"image"];
            result.wight = resp.content[@"width"];
            result.hight = resp.content[@"height"];
            result.messageTime = sendMsgTime;
        }else if (resp.failure){
            [self upDataToDBWithFailure:fuid MessageTime:sendMsgTime];
            
            result.failure = YES;
        }
        [result invoke];
    }];

}
//拉取遗失数据
-(void)loadLoseChatData:(HDChatRangeResult*)result People:(NSString*)fuid Params:(NSDictionary*)params OwnerAddId:(NSString*)ownerAddId MessageTime:(NSString*)messageTime
{
    if ([self.jkHttp isRunning]) {
        return;
    }
    
    NSString * url_str = [NSString stringWithFormat:@"%@%@&startid=%@&endid=%@",self.uniteUrl.im_chatLoseData,[params objectForKey:@"pmid"],[params objectForKey:@"startid"],[params objectForKey:@"endid"]];
    
    [self.jkHttp get:url_str result:^(JKResponse *resp) {
        
        if (resp.OK) {
            
            result.success = YES;
            [self ChatOBODataSourceWithArray:resp.content[@"data"] Peopleid:fuid SendMsgTime:messageTime OwnerAddId:ownerAddId];
            
        }else if (resp.failure){
            
            result.failure = YES;
        }
        [result invoke];
        
    }];
    
}





-(void)ChatOBODataSourceWithArray:(NSArray*)array Peopleid:(NSString*)fuid SendMsgTime:(NSString*)sendMsgTime OwnerAddId:(NSString*)ownerAddId
{
//    DLog(@"time = %@",sendMsgTime);
    [self.mutableArray removeAllObjects];
    [self createFmdbWithPmid:fuid];
    
    for (NSDictionary * dict in array) {
        
        HDMessageModel * model = [HDMessageModel modelWithDict:dict];
        [self.mutableArray addObject:model];
        
        if (self.isRefresh.integerValue == 1) {
            
            [self upDataToDB:model PeoPleid:fuid MessageTime:sendMsgTime OwnerAddId:ownerAddId];
        }else{
            [self saveDataToDB: model Peopleid:fuid OwnerAddId:ownerAddId];
        }
        
        
    }
}

#pragma mark - 立即插入到数据库
-(void)saveDatetoDBWithPeople:(NSString*)fuid Array:(NSArray*)array ListDic:(NSDictionary*)listDic
{
 
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        NSString * sql_insert = [NSString stringWithFormat:@"insert into Chat_%@_%@(ownerAddId, time, content, fuid, uid, msgid, lastid, picture, omit, omitid, type, mtype, extends, flower, red) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]]  ;
        if ([db executeUpdate:sql_insert withArgumentsInArray:array]) {
            DLog(@"保存成功到Chat_fuid表中");
            //打开List表
            NSString * sql_cList = [NSString stringWithFormat:@"create table if not exists ChatList_%@(uid TEXT PRIMARY KEY ,pmid TEXT,name TEXT ,face TEXT, lastTalk TEXT,time TEXT, ownerAddId TEXT,msgid TEXT,omit TEXT, omitid TEXT,delSign TEXT);",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
            if ([db executeUpdate:sql_cList]) {
            
                NSString* sql_upList = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET  name = '%@',face = '%@',lastTalk = '%@',time = '%@' WHERE uid = '%@' ",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"],[listDic objectForKey:@"name"],[listDic objectForKey:@"face"],[listDic objectForKey:@"lastTalk"],[listDic objectForKey:@"time"],[listDic objectForKey:@"uid"]];
                if ([db executeUpdate:sql_upList]) {
                    DLog(@"更新List表成功");
                }
                
                
            }
            
            
        }
        
        
    }];
    
    
    
}

#pragma mark - 更新
-(void)upDataToDB:(HDMessageModel*)model PeoPleid:(NSString*)fuid MessageTime:(NSString*)sendMsgTime OwnerAddId:(NSString*)ownerAddId
{

    
    [self.snFmdbManager.fmdbQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        NSString *returnString=[model.extends JSONString];
        
        NSString * sql = [NSString stringWithFormat:@"UPDATE Chat_%@_%@ SET time = '%@', content = '%@',fuid = '%@',uid = '%@',msgid = '%@',lastid = '%@',picture = '%@',omit = '%@',omitid = '%@',type = '%@',mtype = '%@',extends = '%@',flower = '%@',red = '%@' WHERE ownerAddId = '%@'",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],model.time,model.content,model.fuid,model.uid,model.msgid,model.lastid,model.picture,@"0",model.msgid,model.type,model.myType,returnString,model.flower,model.red,ownerAddId];
        
        
        if ([db executeUpdate:sql]) {
            DLog(@"成功更新Chat_fuid表");
            
            NSString* sql_upList = [NSString string];
            if (model.uid.integerValue == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
                sql_upList = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@',time = '%@',msgid = '%@',omit = '%@',omitid = '%@', delSign = '%@' WHERE uid = '%@'",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],model.pmid,model.time,model.msgid,@"0",model.msgid,@"000",model.fuid];
            }else
            {
                 sql_upList = [NSString stringWithFormat:@"UPDATE ChatList_%@ SET pmid = '%@',time = '%@',msgid = '%@',omit = '%@',omitid = '%@', delSign = '%@' WHERE uid = '%@'",[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],model.pmid,model.time,model.msgid,@"0",model.msgid,@"000",model.uid];
            }
            if ([db executeUpdate:sql_upList]) {
                DLog(@"更新List表成功");
            }
            
            
            
        }
       
    }];
    
//    self.mutableArray = [self arrayFromFmdbWithPmid:fuid];
}
//失败更新数据库
-(void)upDataToDBWithFailure:(NSString *)fuid MessageTime:(NSString*)sendMsgTime
{
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        
//        NSString * sql = [NSString stringWithFormat:@"UPDATE Chat_%@ SET flower = '%@' ,red = '%@' WHERE time = '%@' ",fuid,@"000",@"111",sendMsgTime];
//        
//        if ([db executeUpdate:sql ]) {
//            DLog(@"更新成功到Chatuid表中");
//        }
//        [db close];
//    }];
//    [self.fmdbQueue close];
    NSString * sql = [NSString stringWithFormat:@"UPDATE Chat_%@_%@ SET flower = '%@' ,red = '%@' WHERE time = '%@' ",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"],@"000",@"111",sendMsgTime];
    [self.snFmdbManager performExecuteUpdateWithSql:sql];
    
}

//直接保存到数据库
-(void)saveDataToDB:(HDMessageModel*)model Peopleid:(NSString*)fuid OwnerAddId:(NSString*)ownerid
{

    NSString * sql = [NSString stringWithFormat:@"insert into Chat_%@_%@(ownerAddId, time, content, fuid, uid, msgid, lastid, picture, omit, omitid, type, mtype, extends, flower, red) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
//    DLog(@"flower = %@ red = %@",model.flower,model.red);
    
    NSString *returnString=[model.extends JSONString];
    
    NSArray * dataArray = @[ownerid,model.time,model.content,model.fuid,model.uid,model.msgid,model.lastid,model.picture,@"0",model.msgid,model.type,model.myType,returnString,model.flower,model.red];
    [self.snFmdbManager performExecuteUpdateWithSql:sql withArguments:dataArray];
    
}
- (void)createFmdbWithPmid:(NSString*)pmid
{


    NSString * sql = [NSString stringWithFormat:@"create table if not exists Chat_%@_%@(ownerAddId TEXT PRIMARY KEY ,time TEXT, content TEXT,fuid TEXT, uid TEXT,msgid TEXT,lastid TEXT,picture TEXT,omit TEXT, omitid TEXT,type TEXT,mtype TEXT,extends TEXT,flower TEXT ,red TEXT);",pmid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]] ;
    [self.snFmdbManager createTableWithSql:sql];
    
}

-(NSMutableArray*)arrayFromFmdbWithPmid:(NSString*)pmid
{
    NSMutableArray * arr1 = [NSMutableArray array];
    NSMutableArray * arr2 = [NSMutableArray array];

    [self.snFmdbManager.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString* sql_one = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'Chat_%@_%@';",pmid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        FMResultSet * set_one = [db executeQuery:sql_one];
        if ([set_one next]){
            NSString * sql = [NSString stringWithFormat: @"select * from Chat_%@_%@;",pmid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
            FMResultSet * set = [db executeQuery:sql];
            [self.mutableArray removeAllObjects];
            while ([set next]) {

                NSString * content = [set stringForColumn:@"content"];
                NSString * lastTalk = [Tool replaceEmojiStr:content];
                lastTalk = [Tool stringByRemoveLineBreakChar:lastTalk];
                
                NSString * time = [set stringForColumn:@"time"];
                NSString * uid = [set stringForColumn:@"uid"];
                NSString * fuid = [set stringForColumn:@"fuid"];
                NSString * msgid = [set stringForColumn:@"msgid"];
                NSString * lastid = [set stringForColumn:@"lastid"];
                NSString * picture = [set stringForColumn:@"picture"];
                NSString * type = [set stringForColumn:@"type"];
                NSString * mytype = [set stringForColumn:@"mtype"];
                NSString * extends = [set stringForColumn:@"extends"];
//                DLog(@"extends = %@",extends);
                NSData *JSONData = [extends dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *extendsDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
                NSString * flower = [set stringForColumn:@"flower"];
                NSString * red = [set stringForColumn:@"red"];
                
                NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:fuid,@"fuid",time,@"dateline",lastTalk,@"content",uid,@"uid",msgid,@"msgid",lastid,@"lastid",picture,@"picture",type,@"type",mytype,@"mtype",extendsDic,@"extends",flower,@"flower",red,@"red", nil];
                
               
                [arr1 addObject:dict];
            
            }
            [set close];
        }
        [set_one close];
//        [db close];
    }];
//    [self.fmdbQueue close];
 
    
    NSString * tableName = [NSString stringWithFormat:@"Chat_%@_%@",pmid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    [arr2 addObjectsFromArray:arr1];
   
    
    NSSortDescriptor*sorter=[[NSSortDescriptor alloc]initWithKey:@"ownerAddId" ascending:YES];
    NSMutableArray *sortDescriptors=[[NSMutableArray alloc]initWithObjects:&sorter count:0];
    NSArray *sortArray=[arr2 sortedArrayUsingDescriptors:sortDescriptors];
    
    for (int i=0; i<[sortArray count]; i++) {
        NSLog(@"排序后----->>%@",[[sortArray objectAtIndex:i] objectForKey:@"ownerAddId"]);
        [self.mutableArray addObject:[HDMessageModel modelWithDict:[sortArray objectAtIndex:i]]];
    }
    
    return self.mutableArray;
    
}

-(NSMutableArray*)arrayFromContentToPicture:(NSString*)pmid
{
    NSMutableArray * arr1 = [NSMutableArray array];
    
    [self.snFmdbManager.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString* sql_one = [NSString stringWithFormat:@"select * from sqlite_master where name  = 'Chat_%@_%@';",pmid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
        FMResultSet * set_one = [db executeQuery:sql_one];
        if ([set_one next]){
            NSString * sql = [NSString stringWithFormat: @"select * from Chat_%@_%@;",pmid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
            FMResultSet * set = [db executeQuery:sql];
            [self.mutableArray removeAllObjects];
            while ([set next]) {
                
                NSString * picture = [set stringForColumn:@"picture"];
//                if ([picture rangeOfString:@"http"].location !=NSNotFound){
                [arr1 addObject:picture];
//                }
            }
            [set close];
        }
        [set_one close];
        //        [db close];
    }];
   
    
    return arr1;
    
    
}


-(BOOL)fmdbIncludeChatPeople:(NSString*)fuid
{

    NSString * tableName = [NSString stringWithFormat:@"Chat_%@_%@",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
   return  [self.snFmdbManager fmdbIncludetableWithTableName:tableName];


}

-(BOOL)fmdbInculdeContentDataWithPeople:(NSString *)fuid
{

    NSString * tableName = [NSString stringWithFormat:@"Chat_%@_%@",fuid,[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]];
    return [self.snFmdbManager tabelIncludeDataWithTableName:tableName];
    
}

-(void)deleteDataToDb:(NSString*)fuid WithTime:(NSString*)MsgTime
{
//    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
//        NSString * sql = [NSString stringWithFormat:@"DELETE FROM Chat_%@ WHERE time = %@;",fuid,MsgTime] ;
//        if ([db executeUpdate:sql]) {
////            DLog(@"删除成功");
//        }
////        [db close];
//    }];
////    [self.fmdbQueue close];

}

@end





















